<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyProcessingListDetailsDeliveryLogTable;
use App\Http\Models\Mysql\SsyProcessingListDetailsTable;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class downloadDelivery extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:downloadDelivery {--start=} {--end=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导出出库列表(北岱称重出库记录数据)';

    protected $_cellName = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '1024M');
        $start = $this->option("start") ?? "";
        $end = $this->option("end") ?? "";
        if(empty($start) || empty($end)){
            die("请输入导出时间, --start=, --end=");
        }
        $filename = "出库列表_{$start}_{$end}.xls";
        $file = storage_path("cache/").$filename;
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $header = [
            ['courier_number','快递单号'],
            ['number','RFID唯一码'],
            ['createtime','出库时间'],
            ['type_name','款名'],
            ['sku_code','sku编码']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $i = 0;
        $numIndex = 2;
        while (true){
            $start1 = date('Y-m-d 00:00:00', strtotime("+ $i day".$start));
            $start2 = date('Y-m-d 23:59:59', strtotime("+ $i day".$start));
            if($start1 > date('Y-m-d 00:00:00', strtotime($end))){
                break;
            };
            $field = ['courier_number', 'numberarr', 'createtime'];
            $list = (new SsyProcessingListDetailsDeliveryLogTable())->whereBetween('createtime', [$start1, $start2])->get($field)->toArray();
            $total = count($list);
            foreach ($list as $lIndex => $item){
                $numberArr = unserialize($item['numberarr']);
                if(empty($numberArr)){
                    continue;
                }
                foreach ($numberArr as $nItem){
                    echo "正在写入: {$start1} {$start2} [{$total}, ".($lIndex+1)."]{$nItem['number']}\n";
                    $rfidObj = (new SsyProcessingListDetailsTable())->where('number', $nItem['number'])->first();
                    $rfidObj = !empty($rfidObj) ? $rfidObj->toArray() : [];
                    $data = [
                        'courier_number' => " ".$item['courier_number'],
                        'number' => $nItem['number'],
                        'createtime' => $item['createtime'],
                        'type_name' => $rfidObj['type_name'] ?? "",
                        'sku_code' => $rfidObj['sku_code'] ?? "",
                    ];
                    foreach ($header as $hIndex => $hItem){
                        $sheet->setCellValue($this->_cellName[$hIndex].$numIndex, $data[$hItem[0]]);
                    }
                    $numIndex++;
                }
            }
            $i++;
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        die("处理结束！！！");
    }
}
